﻿using AutoMapper;
using KayakMes.Common;
using KayakMes.Common.Dtos.ProductionDTO.Input;
using KayakMes.Common.Dtos.ProductionDTO.Output;
using KayakMes.Common.Result;
using KayakMes.ProcessStepUp.Domain.ProductionModel;
using System;
using System.Collections.Generic;
using System.Linq;
using Yitter.IdGenerator;

namespace KayakMes.ProcessManagement.Application.Production
{
    public class ProductionService : IProductionService
    {
        private readonly BaseReposiotry<ProductionOrderModel> _productionOrderRepository;
        private readonly IMapper _mapper;
        private static readonly object _codeLock = new object();

        public ProductionService(BaseReposiotry<ProductionOrderModel> productionOrderRepository, IMapper mapper)
        {
            _productionOrderRepository = productionOrderRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加生产订单
        /// </summary>
        /// <param name="input">生产订单输入模型</param>
        /// <returns>返回操作结果</returns>
        public ApiResult<int> AddProductionOrder(ProductionOrderInput input)
        {
            // 创建新的生产订单
            var productionOrder = _mapper.Map<ProductionOrderModel>(input);
            productionOrder.Id = YitIdHelper.NextId();
            productionOrder.CreateTime = DateTime.Now;
            productionOrder.IsDeleted = false;
            var result = _productionOrderRepository.Add(productionOrder);
            if (result > 0)
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Success, 
                    Message = "添加生产订单成功", 
                    Data = result 
                };
            }
            else
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Fail, 
                    Message = "添加生产订单失败", 
                    Data = 0 
                };
            }
        }

        /// <summary>
        /// 更新生产订单
        /// </summary>
        /// <param name="input">生产订单输入模型</param>
        /// <returns>返回操作结果</returns>
        public ApiResult<int> UpdateProductionOrder(UpdateProductionOrderInput input)
        {
            // 检查订单是否存在
            var existOrder = _productionOrderRepository.GetModel(input.Id);
            if (existOrder == null || existOrder.IsDeleted)
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.NotFound, 
                    Message = "生产订单不存在", 
                    Data = 0 
                };
            }
            // 更新订单信息
            _mapper.Map(input, existOrder);
            existOrder.UpdateTime = DateTime.Now;

            var result = _productionOrderRepository.Update(existOrder);
            if (result > 0)
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Success, 
                    Message = "更新生产订单成功", 
                    Data = result 
                };
            }
            else
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Fail, 
                    Message = "更新生产订单失败", 
                    Data = 0 
                };
            }
        }

        /// <summary>
        /// 删除生产订单
        /// </summary>
        /// <param name="id">生产订单ID</param>
        /// <returns>返回操作结果</returns>
        public ApiResult<int> DeleteProductionOrder(long id)
        {
            var existOrder = _productionOrderRepository.GetModel(id);
            if (existOrder == null || existOrder.IsDeleted)
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.NotFound, 
                    Message = "生产订单不存在", 
                    Data = 0 
                };
            }

            // 软删除
            existOrder.IsDeleted = true;
            existOrder.UpdateTime = DateTime.Now;

            var result = _productionOrderRepository.Update(existOrder);
            if (result > 0)
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Success, 
                    Message = "删除生产订单成功", 
                    Data = result 
                };
            }
            else
            {
                return new ApiResult<int> 
                { 
                    Code = ApiEnums.Fail, 
                    Message = "删除生产订单失败", 
                    Data = 0 
                };
            }
        }

        /// <summary>
        /// 获取生产订单列表
        /// </summary>
        /// <param name="input">查询条件</param>
        /// <returns>返回分页结果</returns>
        public ApiPaging<ProductionOrderOutput> GetProductionOrders(GetProductionOrderInput input)
        {
            //ApiPaging<ProductionOrderOutput> apiPaging = new ApiPaging<ProductionOrderOutput>();
            
            var query = _productionOrderRepository.GetAll().Where(x => !x.IsDeleted);
            
            // 应用查询条件
            if (!string.IsNullOrEmpty(input.OrderNumber))
            {
                query = query.Where(x => x.OrderNumber.Contains(input.OrderNumber));
            }
            
            if (!string.IsNullOrEmpty(input.OrderName))
            {
                query = query.Where(x => x.OrderName.Contains(input.OrderName));
            }
            
            if (!string.IsNullOrEmpty(input.ProductCode))
            {
                query = query.Where(x => x.ProductCode.Contains(input.ProductCode));
            }
            
            if (!string.IsNullOrEmpty(input.ProductName))
            {
                query = query.Where(x => x.ProductName.Contains(input.ProductName));
            }
            
            if (!string.IsNullOrEmpty(input.CustomerName))
            {
                query = query.Where(x => x.CustomerName.Contains(input.CustomerName));
            }
            
            if (input.RequiredDate.HasValue)
            {
                query = query.Where(x => x.PlannedProductionDate.Date == input.RequiredDate.Value.Date);
            }

            var list = query.OrderBy(x => x.Id)
                .Skip((input.PageIndex - 1) * input.PageSize)
                .Take(input.PageSize)
                .ToList();

            var entity = _mapper.Map<List<ProductionOrderOutput>>(list);

            // 设置分页信息
            int total = query.Count();

            return new ApiPaging<ProductionOrderOutput>
            {
                Items = entity,
                Total = total,
                Code = ApiEnums.Success,
                Message = "获取成功",
                PageIndex = input.PageIndex,
                PageSize = input.PageSize,
            };
            
            
        }

        /// <summary>
        /// 根据ID获取生产订单
        /// </summary>
        /// <param name="id">生产订单ID</param>
        /// <returns>返回操作结果</returns>
        public ApiResult<ProductionOrderOutput> GetProductionOrderById(long id)
        {
            var order = _productionOrderRepository.GetModel(id);
            
            if (order == null || order.IsDeleted)
            {
                return new ApiResult<ProductionOrderOutput> 
                { 
                    Code = ApiEnums.NotFound, 
                    Message = "生产订单不存在", 
                    Data = null 
                };
            }
            
            var output = _mapper.Map<ProductionOrderOutput>(order);
            
            return new ApiResult<ProductionOrderOutput> 
            { 
                Code = ApiEnums.Success, 
                Message = "获取生产订单成功", 
                Data = output 
            };
        }
    }
}